import React, { useEffect, useState } from 'react'
import { Button, Space, Table, message, } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DELOneUserCheck, GetRoomTimer, GetRoomUserMsg, UserLostCard } from '../service';
import '../indexRoom.less'
import { useDispatch, useSelector } from 'react-redux';
import { changeBULostCard, decrement } from '../counter/counterSlice';
import { useDeleteConfirm } from '@/hooks/useAlartMolder';
// import UserModel from './userModel';
// import UserModel from '../components/userModel'
import { useIntl } from '@umijs/max';

interface userprpos {
  userMsg: UserData[] | any;
  dataMsg: UserData[] | any
  setuserMsgInfo: (event: UserFaka) => void
  setuseMsgFlag: (event: boolean) => void
  setuserListLength: (event: string) => void
  setUserNocardIssued: (event: UserData[]) => void
  setsendMsg: (event: stateObj) => void
  setType: (event: string) => void

}

const CurrentUser: React.FC<userprpos> = ({
  setUserNocardIssued, userMsg,
  dataMsg, setuserMsgInfo,
  setuserListLength,
  setType, setsendMsg
}) => {
  const intl = useIntl();
  const columns: ColumnsType<UserData> = [
    {
      key: "realName",
      title: intl.formatMessage({ id: "business.Name" }),
      dataIndex: 'realName',
      filterMode: 'tree',
      filterSearch: true,

    },
    {
      key: "roomNo",
      title: intl.formatMessage({ id: "business.Room" }),
      render: (_, record: { subRoomNo: string; roomNo: string }) => (record.subRoomNo ? record.subRoomNo : record.roomNo),

    },
    {
      key: "mobile",
      title: intl.formatMessage({ id: "business.Mobile" }),
      dataIndex: 'mobile',
      align: "center",
    },
    {
      key: "cardNum",
      title: intl.formatMessage({ id: "business.Room card" }),
      dataIndex: 'cardNum',
      align: "center",
    },
    {
      key: "issuingTime",
      title: intl.formatMessage({ id: "business.Card issuance time" }),
      dataIndex: 'issuingTime',
      filterSearch: true,
      align: "center",
    },
    {
      title: intl.formatMessage({ id: "business.Issuing" }),
      key: 'actiontwo',
      align: "center",
      dataIndex: 'status',
      width: 80,
      render: (_, record) => (
        <Space size="middle">
          {
            record.status == '1' ? (
              <a style={{ color: "green" }}> {intl.formatMessage({ id: "business.Success" })}</a>
            ) : record.status == "0" ? (
              <a style={{ color: "#28004D" }}>{intl.formatMessage({ id: "business.wait" })}</a>
            ) : record.status == "7" ? (
              <a style={{
                color: "#708090"
              }}>{intl.formatMessage({ id: "business.lost" })}</a>
            ) : (
              <a style={{ color: "red" }}>{intl.formatMessage({ id: "business.Return card" })}</a>
            )
          }
        </Space>
      ),
    },
    {
      title: intl.formatMessage({ id: "business.Action" }),
      key: 'action',
      align: "center",
      width: 115,
      render: (_, record) => (
        <Space size="middle">
          {
            record.status == '1' ? (
              // <Dropdown menu={{ items }} placement="bottom" arrow>
              <a style={{ color: "red" }} onClick={() => LostCard(record)}>{intl.formatMessage({ id: "business.Loss" })}</a>
              // </Dropdown>
            ) : record.status == "0" ? (
              <a style={{ color: "red" }} onClick={(() => {
                ISDELOneUserCheck(record)

              })}>{intl.formatMessage({ id: "business.Delete" })}</a>
            ) : record.status == "7" ? (
              <Button size="small" style={{ fontSize: "12px" }} onClick={(() => {
                ReplacementCard(record)

              })}>{intl.formatMessage({ id: "business.mend card" })}</Button>
            ) : (
              <a style={{ color: "red" }}></a>
            )
          }
        </Space>
      ),
    },
  ];

  // 
  const ReplacementCard = async (data: any) => {
    let result = await GetRoomTimer(userMsg.roomId)
    if (result.code == 0) {
      let res = JSON.parse(data.cmdInfo)
      let SENDData = { ...res, begintime: result.data.expire_date }
      dispatch(changeBULostCard(data))
      setsendMsg(SENDData)
      setType("补卡成功")
    }
  }

  const LostCard = (data: { realName: string; roomId: string }) => {
    useDeleteConfirm( intl.formatMessage({ id: 'business.Room Card Loss' }, { Guest: data.realName }), "", async (res) => {
      if (res == true) {
        let result = await UserLostCard(data.roomId)
        if (result.code == 0) {
          message.success(intl.formatMessage({ id: "Loss Success" }))
          getusermsg()
        }
      }
    })
  }
  const ISDELOneUserCheck = async (data: { UUID: string; id: string }) => {
    if (data.UUID) {
      let list = userList.filter((item) => {
        return item.UUID != data.UUID
      })
      setUserList(list)
    } else {
      let result = await DELOneUserCheck(data.id)
      if (result.code == 0) {
        getusermsg()
        if (!userList.length) {
          setUserList([])
        }
      }
    }
  }
  const dispatch = useDispatch()
  const value = useSelector(state => state.counter.value)
  useEffect(() => {
    if (value == true) {
      getusermsg()
    }
  }, [value])
  const [userList, setUserList] = useState<UserData[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[] | any>(); // 获取选中数据的下标 并且高亮
  const _ = require('lodash');
  const getusermsg = async () => {
    dispatch(decrement())

    let { data } = await GetRoomUserMsg(userMsg.roomId)
    if (data.list) {
      setUserList(data.list)

      let number = data.list.map((item: { status: string; }) => {
        return item.status
      })
      // 查看还有多少房卡再用
      const count = _.filter(number, (num: number) => num === 1).length;
      setuserListLength(count)
      const indexUsingFindIndex = _.findIndex(number, (num: number) => num === 1);
      setSelectedRowKeys([indexUsingFindIndex]);
      setuserMsgInfo(data.list[indexUsingFindIndex])

    }
    // 点击进入 选中还未退卡的第一条记录
    if (userMsg.cardNum) {
      if (data.list) {
        var index = data.list.findIndex(function (obj: { cardNum: string }) {
          return obj.cardNum === userMsg.cardNum
        });
        setSelectedRowKeys([index]);
      }
    }

  }


  useEffect(() => {
    getusermsg()
  }, [])

  useEffect(() => {
    if (dataMsg) {
      const newDataMsg = { ...dataMsg, idd: Date.now().toString() }; // 添加唯一id
      setUserList((prevList: any) => [newDataMsg, ...prevList,]);
      setSelectedRowKeys([0]); // 设置默认选择的行为新增的最后一行
    }
  }, [dataMsg]);


  useEffect(() => {
    setUserNocardIssued(userList)
    setuserMsgInfo(userList[selectedRowKeys])
  }, [selectedRowKeys])

  return (
    <div>
      <Table
        className='menustyle'
        style={{
          width: "860px",
          height: "300px",
          overflowY: "auto",
          msOverflowStyle: "none",
          scrollbarWidth: "none"
        }}
        columns={columns}
        dataSource={userList.map((item: UserData, index) => ({
          ...item,
          key: index,
        }))}
        pagination={false}
        rowSelection={{
          type: 'radio',
          selectedRowKeys,
          onChange: (keys: React.Key[]) => setSelectedRowKeys(keys),
        }}
        onRow={(record) => ({
          onClick: () => {
            const newSelectedRowKeys = [record.key];
            setSelectedRowKeys(newSelectedRowKeys);
          },
        })}
      />
      {/* 

      {
        isModalOpen == true && <UserModel isModalOpen={isModalOpen} handleOneuseMsg={handleOneuseMsg} OneuseMsg={OneuseMsg} />
      } */}
    </div>
  )
}

export default CurrentUser